package com.example.farmer.wode;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.example.farmer.Adapter.CartAdapter;
import com.example.farmer.Database.CartDatabase;
import com.example.farmer.Entity.CartItem;
import com.example.farmer.R;

import java.util.ArrayList;
import java.util.List;

public class CarActivity extends AppCompatActivity {
    private ListView cartListView;
    private CartAdapter cartAdapter;
    private List<CartItem> cartItems;
    private ImageButton back;
    private TextView totalPriceView;
    private CheckBox selectAllCheckbox;
    private Button checkoutButton;
    private CartDatabase cartDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart); // 确保使用正确的布局文件名


        back = findViewById(R.id.back_button);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 初始化ListView和适配器
        cartListView = findViewById(R.id.cart_list);
        cartItems = new ArrayList<>();

        //从数据库获取商品
        cartDatabase = CartDatabase.getInstance(this);
        cartItems = cartDatabase.getAllCartItems();

        cartAdapter = new CartAdapter(this, cartItems);
        cartListView.setAdapter(cartAdapter);

        // 初始化底部操作栏的组件
        totalPriceView = findViewById(R.id.total_price);
        selectAllCheckbox = findViewById(R.id.select_all);
        checkoutButton = findViewById(R.id.checkout_button);

        // 设置全选复选框的事件监听器
        selectAllCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            cartAdapter.setAllSelected(isChecked);
            calculateTotalPrice();
        });

        // 设置结算按钮的点击事件
        checkoutButton.setOnClickListener(v -> {
            // 执行结算操作
            // 这里可以添加跳转到结算页面的逻辑
        });

        // 计算总价并更新显示
        calculateTotalPrice();
    }

    private void calculateTotalPrice() {
        double totalPrice = 0;
        for (CartItem item : cartItems) {
            if (selectAllCheckbox.isChecked() || cartAdapter.isSelected(item.getId())) {
                totalPrice += item.getPrice() * item.getQuantity();
            }
        }
        totalPriceView.setText("合计：¥" + String.format("%.2f", totalPrice));
    }
}